const app = getApp();
import {
  sendFileToLianke,
  refundRequest,
  getPrintJobStatus,
  getJobListByOrderId,
  selectPrinterInfo
} from "../../common/api";

Page({
  data: {
    jobLists: [],
    ext: {
      jpeg: {
        icon: "../../images/JPG@2x.png",
        color: "#6CE4D8"
      },
      jpg: {
        icon: "../../images/JPG@2x.png",
        color: "#6CE4D8"
      },
      png: {
        icon: "../../images/PNG@2x.png",
        color: "#FFD93B"
      },
      xls: {
        icon: "../../images/XLSX@2x.png",
        color: "#9ED463"
      },
      xlsx: {
        icon: "../../images/XLSX@2x.png",
        color: "#9ED463"
      },
      ppt: {
        icon: "../../images/PPT@2x.png",
        color: "#F8A53B"
      },
      pptx: {
        icon: "../../images/PPT@2x.png",
        color: "#F8A53B"
      },
      pdf: {
        icon: "../../images/PDF@2x.png",
        color: "#EF427C"
      },
      doc: {
        icon: "../../images/DOC@2x.png",
        color: "#5E7EE8"
      },
      docx: {
        icon: "../../images/DOC@2x.png",
        color: "#5E7EE8"
      }
    },
  },
  onLoad: function (options) {
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      });
    }
    if (options.printerId) {
      this.setData({
        printerId: options.printerId
      });
    }
  },
  onShow: function () {
    let printer = app.globalData.printer
    if (printer == undefined) {
      // 获取打印机
      selectPrinterInfo(this.data.printerId).then(res => {
        if (res.code == 200) {
          this.setData({
            printer_name: `${app.globalData.printer.printerName}(${app.globalData.printer.shopName})`,
            printer: app.globalData.printer,
          })
          this.initData();
        }
      })
    } else {
      this.setData({
        printer_name: `${app.globalData.printer.printerName}(${app.globalData.printer.shopName})`,
        printer: app.globalData.printer,
      })
      this.initData();
    }
  },
  initData() {
    let data = {
      "printStatus": 1,
      "orderId": this.data.orderId
    }
    getJobListByOrderId(data).then(res => {
      console.log("获取打印列表", res);
      if (res.code == 200) {
        this.setData({
          jobLists: res.data.jobLists
        });
        this.sendPrinterTask();
        if (res.data.length == 0) {
          wx.showModal({
            content: res.msg,
            success: _ => {
              wx.reLaunch({
                url: '/pages/index/index',
              })
            }
          })
        }
      }
    })

  },
  //创建打印任务
  sendPrinterTask() {
    let lists = this.data.jobLists;
    console.log(lists)
    let sendLists = [...lists];
    this.setData({
      sendLists: sendLists
    });
    this.setSend();
  },
  //发送打印任务
  setSend() {
    //1.取出第个待打印的文件,
    let sendLists = this.data.sendLists;
    if (sendLists.length === 0) {
      return;
    }
    let printerId = this.data.printer.id;
    //2.发送打印任务
    let data = {
      orderId: this.data.orderId,
      printerId: printerId
    }
    sendFileToLianke(data).then(res => {
      console.log("获取打印taskId", res)
      if (res.code == 200) {
        this.setData({
          sendLists: sendLists
        });
        this.timer = setInterval(_ => {
          //3.每隔10秒查询打印状态,更新打印状态
          getPrintJobStatus(data).then(res => {
            //打印状态查询成功  
            if(res.code != 200){
              clearInterval(this.timer)
              return;
            }
            this.setData({
              jobLists: res.data.jobLists
            });
            //4.打印完成
            console.log("获取打印结果", res)
            if (res.data.success) {
              console.log("打印成功退出本次打印", data)
              clearInterval(this.timer)
              wx.showModal({
                title: '打印成功',
                content: '请去我的>我的订单里查看',
                confirmText: '前去查看',
                success(res) {
                  if (res.confirm) {
                    wx.reLaunch({
                      url: '/pages/or_list/index',
                    })
                  }
                }
              })
            }
          }, () => {
            clearInterval(this.timer)
          })
        }, 5000);
      } else {
        this.showAlert(res.msg)
      }
    }).catch(res => {
      //2.2 发送失败,弹出提示,让用户选择退款或重试
      this.showAlert(res.msg)
    })
  },
  showAlert(message) {
    wx.showModal({
      title: "警告",
      content: message,
      cancelText: "申请退款",
      confirmText: "重试",
      success: r => {
        if (r.confirm) {
          //重试
          this.setSend();
        } else {
          //申请退款
          this.orderRefund(this.data.orderId)
        }
      }
    })
  },
  //申请退款(整个订单全部退款)
  orderRefund(orderId) {
    let data = {
      orderId: orderId,
      refundDesc: '打印失败申请退款'
    }
    wx.showLoading({
      title: '申请退款中...',
      mask: true,
    })
    refundRequest(data).then(res => {
      wx.hideLoading();
      console.log(res);
      if (res.code == 200) {
        wx.showModal({
          title: "提示",
          content: "退款申请已提交,订单金额将原路退回!",
          confirmText: "返回首页",
          showCancel: false,
          success: _ => {
            wx.reLaunch({
              url: '../index/index',
            })
          }
        })
      } else {
        wx.showModal({
          content: res.msg,
          showCancel: false,
          confirmText: "返回首页",
          success: _ => {
            wx.reLaunch({
              url: '../index/index',
            })
          }
        })
      }
    })
  },
  navigatorToShop(e) {
    console.log(printer);
    let printer = this.data.printer;
    if (printer == undefined) {
      console.log("未设置默认打印点")
      return
    }
    wx.showModal({
      title: "提示",
      content: "确认导航到打印点？",
      cancelText: "取消",
      confirmText: "去导航",
      success: res => {
        if (res.confirm) {
          let lat = parseFloat(printer.lat);
          let lng = parseFloat(printer.lng);
          wx.openLocation({
            latitude: lat,
            longitude: lng,
          })
        }
      }
    })
  },
})